package initialize

import (
	"encoding/json"
	"errors"
	"fmt"
	"gitee.com/freedom_feel/gui-bos-api/cmd/initialize/client"
	"gitee.com/freedom_feel/gui-bos-api/cmd/middleware"
	"gitee.com/freedom_feel/gui-bos-api/cmd/router"
	"gitee.com/freedom_feel/gui-bos-api/common"
	_type "gitee.com/freedom_feel/gui-bos-api/common/type"
	"gitee.com/freedom_feel/gui-bos-api/global"
	"gitee.com/freedom_feel/gui-bos-api/logs"
	"gitee.com/freedom_feel/gui-bos-api/models"
	"net/http"
	"time"

	"github.com/gin-gonic/gin"
)

func InitGin() {
	//global.JsonData = make(chan string, 1)
	r := gin.Default()
	//测试
	r.GET("/ping", func(c *gin.Context) {
		c.JSON(200, gin.H{
			"message": "pong",
		})
	})
	router.InitStaticRouter(r)
	//r.Use(middleware.AuthMiddleware())
	router.InitUserRouter(r)
	router.InitTaskRouter(r)
	router.InitProductRouter(r)
	router.InitUploadRouter(r)
	r.LoadHTMLGlob("templates/*")
	// 路由
	r.GET("/jobs", func(c *gin.Context) {
		uid, ok := common.VerifyCookie(c.Request.Cookies())
		if !ok {
			//认证不通过 返回
			c.Redirect(http.StatusFound, "/login_page")
			c.Abort()
			return
		}
		get, err := client.RedisGet(uid + "_" + global.DataKey)
		if err != nil {
			logs.Error(err.Error())
			_type.ErrChan <- *_type.ErrSystem(fmt.Sprintf("系统内部错误:%v", err.Error()))
			common.FailErrCode(c, "系统内部错误,请稍后再试.", http.StatusInternalServerError)
			return
		}
		//data := <-global.JsonData
		if get != "" {
			var datas []models.SelectBoss
			json.Unmarshal([]byte(get), &datas)
			var jobs []global.Job
			for _, v := range datas {
				jobs = append(jobs, global.Job{
					Title:          v.BossTitle,
					City:           v.CityName,
					Education:      v.JobDegree,
					Experience:     v.JobExperience,
					Address:        v.Address,
					Salary:         v.SalaryDesc,
					Recruiter:      v.BossName,
					RecruiterTitle: v.BossTitle,
					Company:        v.BrandName,
					CompanySize:    v.BrandScaleName,
					CompanyType:    v.BrandIndustry,
					CompanyStatus:  v.BrandStageName,
					Benefits:       []string{"五险一金", "年终奖", "带薪年假", "定期体检"},
					Description:    common.TruncateString(v.Zwms, 100),
					Responsibilities: []string{
						"参与系统架构设计",
						"高性能服务开发",
						"技术难题攻关",
					},
				})
			}
			c.HTML(http.StatusOK, "jobs.html", gin.H{
				"jobs": jobs,
			})
			return
		}
	}, middleware.AuthMiddleware())

	//超级管理员
	//r.Group("/admin", AuthMiddleware(), AdminMiddleware())
	srv := &http.Server{
		Addr:         ":80",
		Handler:      r,
		ReadTimeout:  30 * time.Second,
		WriteTimeout: 30 * time.Second,
		IdleTimeout:  30 * time.Second,
	}
	//r.Run(":80")
	if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
		fmt.Printf("ListenAndServe error: %v\n", err)
	}
	//fmt.Println("====================================")
}
